
// import { redirectTo } from "@/nav.js";
// import { setToken, getAccessToken, getRefreshToken, getTenantId } from "@/auth.js";
import nav from "/nav.js";
import auth from "/auth.js";

let requestList = []; // 刷新token等待请求队列
let isTokenRefreshing = false; // 标识 token 刷新状态

// 线上环境
const SERVICE_URL = 'http://intuit01.eicp.net'
// const SERVICE_URL = 'https://xsj.opencc.cn'

export default {
  SERVICE_URL,
  // get
  get(url, params, otherParams) {
    return this.requestFun({
      method: "GET",
      url,
      params,
      otherParams
    });
  },

  // post
  post(url, params, otherParams) {
    return this.requestFun({
      method: "POST",
      url,
      params,
      otherParams
    });
  },

  // put
  put(url, params, otherParams) {
    return this.requestFun({
      method: "PUT",
      url,
      params,
      otherParams
    });
  },

  // delete
  delete(url, params, otherParams) {
    return this.requestFun({
      method: "DELETE",
      url,
      params,
      otherParams
    });
  },

  // request 请求
  requestFun({ method, url, params, otherParams }) {
    return new Promise((resolve, reject) => {
      // 请求添加token
      let token = auth.getAccessToken() || "";
      if (!otherParams || (otherParams && otherParams.showLoading !== false)) {
        wx.showLoading();
      }
      console.log(SERVICE_URL + url)
      wx.request({
        url: SERVICE_URL + url,
        method: method,
        data: params,
        header: {
          "content-type": "application/json",
          "Authorization": token ? `Bearer ${token}` : "",
          "tenant-id": ""
        },
        dataType: "json",
        success: res => {
          console.log(res);
          if (!otherParams || (otherParams && otherParams.showLoading !== false)) {
            wx.hideLoading();
          }
          const data = res.data || {};
          const code = data.code || 0;
          if (code === 401) {
            nav.redirectTo("/login/login");
            // 令牌失效
            // if (!isTokenRefreshing) {
            //     this.refreshToken(url).then(() => {
            //         requestList.forEach(cb => {
            //             cb();
            //         });
            //         requestList = [];
            //         this.requestFun({
            //             method,
            //             url,
            //             params
            //         }).then(response => {
            //             resolve(response);
            //         });
            //     });
            // } else {
            //     // 添加到队列，等待刷新获取到新的令牌
            //     return new Promise(resolveFun => {
            //         requestList.push(() => {
            //             resolveFun(
            //                 this.requestFun({
            //                     method,
            //                     url,
            //                     params
            //                 }).then(response => {
            //                     resolve(response);
            //                 })
            //             );
            //         });
            //     });
            // }
          } else if (code !== 0) {
            // console.log(otherParams)
            if (!otherParams || (otherParams && otherParams.errTips !== false)) {
              if (!otherParams || (otherParams && otherParams.showMsg !== false)) {
                wx.showToast({
                  title: data.msg || data.message || "系统繁忙，请稍后再试",
                  icon: "none"
                })
              }else {
                            
              }           
            }
            resolve(res.data);
          } else {
            resolve(res.data);
          }
        },
        fail: error => {
          if (!otherParams || (otherParams && otherParams.showLoading !== false)) {
            wx.hideLoading();
          }
          reject(error);
          console.error("fail: ", JSON.stringify(error));
        }
      });
    });
  },

  // uploadFile 请求
  uploadFile(url, filePath, openId, jndiName, formData, otherParams) {
    return new Promise((resolve, reject) => {
      if (!otherParams || (otherParams && otherParams.showLoading !== false)) {
        wx.showLoading();
      }
      wx.uploadFile({
        url: SERVICE_URL + url,
        // method: "POST",
        name: "pic",
        filePath: filePath,
        formData: formData,
        header: {
          'openId': openId,
          'jndiName': jndiName,
          'Content-Type': 'multipart/form-data',
        },
        success: res => {
          if (!otherParams || (otherParams && otherParams.showLoading !== false)) {
            wx.hideLoading();
          }
          const data = JSON.parse(res.data) || {};
          const code = data.code || 0;
          if (code === 401) {
            if (!isTokenRefreshing) {
              this.refreshToken(url).then(() => {
                requestList.forEach(cb => {
                  cb();
                });
                requestList = [];
                this.uploadFile(url, filePath, formData).then(
                  res => {
                    resolve(res);
                  }
                );
              });
            } else {
              // 添加到队列，等待刷新获取到新的令牌
              return new Promise(resolveFun => {
                requestList.push(() => {
                  resolveFun(
                    this.uploadFile(
                      url,
                      filePath,
                      formData
                    ).then(response => {
                      resolve(response);
                    })
                  );
                });
              });
            }
          } else if (code !== 0) {
            wx.showToast({
              content: data.msg || data.message || "系统繁忙，请稍后再试"
            });
            resolve(res);
          } else {
            resolve(res);
          }
        },
        fail: function(error) {
          if (!otherParams || (otherParams && otherParams.showLoading !== false)) {
            wx.hideLoading();
          }
          reject(error);
          console.error("fail: ", JSON.stringify(error));
        }
      });
    });
  },

  // 刷新token
  refreshToken(url) {
    let token = auth.getRefreshToken() || "";
    // 忽略接口地址（token失效留在当前页）
    let ignoreUrl = [];
    isTokenRefreshing = true;
    // auth.setToken({
    //     accessToken: "",
    //     // refreshToken: ""
    // });
    return new Promise((resolve, reject) => {
      // 获取不到刷新的令牌
      if (!token) {
        if (url && ignoreUrl.indexOf(url) !== -1) {
          return;
        }
        isTokenRefreshing = false;
        nav.redirectTo("/login/login");
        reject();
        return;
      }
      this.post("/app-open-api/system/auth/manage/refresh-token?refreshToken=" +token
      ).then(res => {
        const code = res.code;
        const data = res.data;
        if (code == 0 && data.accessToken) {
          auth.setToken(data);
          resolve(res);
        } else if (url && ignoreUrl.indexOf(url) !== -1) {
          wx.hideToast();
        } else {
          // 无效的刷新令牌 或 获取令牌失败
          requestList = [];
          nav.redirectTo("/login/login");
        }
        isTokenRefreshing = false;
      }).catch(error => {
        requestList = [];
        isTokenRefreshing = false;
        reject(error);
      });
    });
  },

};
